<template>
	<gracePage :customHeader="false">
		<!-- 使用自定义底部导航时为主体增加底部 padding 避免遮盖 -->
		<view slot="gBody" class="grace-body" style="padding-bottom:150rpx;padding-top:40rpx;">
			<step :active="0"></step>
			<!-- 购物车为空 -->
			<view v-if="shoppingCard.length < 1" style="margin-top:150px;">
				<graceEmpty>
					<view slot="img" class="empty-view">
						<!-- 请根据您的项目要求制作并更换为空图片 -->
						<image class="empty-img" mode="widthFix" src="https://staticimgs.oss-cn-beijing.aliyuncs.com/empty.png"></image>
					</view>
					<text slot="text" class="grace-text-small grace-gray">您的购物车空空如也~</text>
				</graceEmpty>
			</view>
			<!-- 购物车主结构  -->
			<view class="grace-shoppingcard" v-for="(item, index) in shoppingCard" :key="index">
				<view class="grace-space-between grace-flex-vcenter">
					<view class="grace-shopp-name">
						<graceCheckBtn @change="shopChange" :parameter="[index]" :checked="item.checked">
							<text class="grace-h5 grace-bold">{{item.name?item.name:'暂无店铺名称'}}</text>
						</graceCheckBtn>
					</view>
					<view v-if="item.name" class="grace-shopp-go grace-nowrap grace-flex-end" @click="go('./index?id='+item.id)">
						<text class="grace-text-small">进店</text>
						<text class="grace-text-small grace-icons icon-arrow-right"></text>
					</view>
				</view>
				<view style="height:25rpx;"></view>
				<view class="grace-shoppingcard-goods" v-for="(goods, indexItem) in item.list" :key="indexItem" @touchstart="msgtouchstart"
				 @touchend="msgtouchend" @touchmove="msgtouchmove">
					<view class="grace-shoppingcard-goods-checkbtn">
						<graceCheckBtn :checked="goods.checked" @change="itemChange" :parameter="[index+'-'+indexItem]"></graceCheckBtn>
					</view>
					<image :src="goods.logo" @tap="go('/pages/goods/details?id='+goods.id)" class="grace-shoppingcard-goods-image"
					 mode="widthFix"></image>
					<view class="grace-shoppingcard-goods-body">
						<view @tap="go('/pages/goods/details?id='+goods.id)" class="grace-shoppingcard-goods-title">{{goods.title}}</view>
						<view @tap="go('/pages/goods/details?id='+goods.id)" class="gg">{{goods.sku_name?'规格：'+goods.sku_name:''}}</view>
						<view class="grace-space-between">
							<text @tap="go('/pages/goods/details?id='+goods.id)" class="grace-shoppingcard-goods-price">￥{{goods.money}}</text>
							<view class="grace-shoppingcard-goods-number">
								<view style="margin-right:20rpx;" class="numbutton" @tap="clearNum(goods,index,indexItem,item)">-</view>
								<view class="num">{{goods.buyNum}}</view>
								<view style="margin-left:20rpx;" class="numbutton" @tap="addNum(goods,index,indexItem,item)">+</view>
								<!-- <graceNumberBox :disabled="true" :index="indexItem" :datas="index+''" inputPadding="5rpx" 
								:value="goods.buyNum" :maxNum="100" :minNum="1" v-on:change="numberChange"></graceNumberBox> -->
							</view>
						</view>
						<text class="grace-shoppingcard-remove grace-icons icon-remove" @tap="removeGoods($event,goods.cartId)" :id="'removeIndex_' + index + '_' + indexItem">删除</text>
					</view>
				</view>
			</view>
		</view>
		<view slot="gFooter" class="grace-nowrap grace-flex-vcenter grace-border-t" style="background-color:#FFFFFF;">
			<view class="grace-shoppingcard-checkbtn grace-nowrap grace-flex-vcenter">
				<graceCheckBtn v-if="shoppingCard.length>=1" :checked="allChecked" @change="itemChangeAll">
					<text class="grace-text" style=" color:#ed1475;">{{selectText}}</text>
				</graceCheckBtn>
				<graceCheckBtn v-else :checked="false" @change="itemChangeAll">
					<text class="grace-text">{{selectText}}</text>
				</graceCheckBtn>
			</view>
			<view class="grace-shoppingcard-count grace-nowrap grace-flex-vcenter">
				<text class="grace-text" style=" color:#ed1475;">合计 :</text>
				<text style="font-size:24rpx; color:#ed1475;">￥{{totalprice}}</text>
			</view>
			<view  class="grace-shoppingcard-checkout " style="color:#ed1475;background: #fff;border-left:1px solid #eee;" @tap="go('/pages/goods/index')">到处逛逛</view>
			<view  class="grace-shoppingcard-checkout " style="background: #ed1475;color:#fff;" @tap="checkout">结算</view>
		</view>
	</gracePage>
</template>
<script>
	import gracePage from "@/graceUI/components/gracePage.vue";
	import graceEmpty from "@/graceUI/components/graceEmptyNew.vue";
	import graceCheckBtn from '@/graceUI/components/graceCheckBtn.vue';
	import graceNumberBox from '@/graceUI/components/graceNumberBox.vue';
	import {
		orderCart,
		deleteOrderCart,
		orderCartChange
	} from '@/api/goods';
	import {
		getAuth
	} from '@/api/user';
	export default {
		data() {
			return {
				// 总价
				totalprice: 0,
				// 选择文本
				selectText: '全选',
				// 购物车数据 可以来自 api 请求或本地数据
				shoppingCard: [],
				dataInfo: {},
				allChecked: true
			}
		},
		onShow() {
			if(this.userInfo){
				this.getOrderCart();
			}
		},
		computed: {
			userInfo() {
				return getAuth();
			}
		},
		methods: {
			getOrderCart() {
				this.countTotoal();
				this.shoppingCard = [];
				let datas = JSON.parse(this.$Shop.getGoodsCart()).data;
				for (var key in datas) {
					if ((typeof datas[key]) == 'object') {
						this.shoppingCard = datas[key];
					} else {
						this.dataInfo[key] = datas[key]
					}
				}
				 for (var i = 0; i < this.shoppingCard.length; i++) {
					this.shoppingCard[i].checked = true;
					for (var ii = 0; ii < this.shoppingCard[i].list.length; ii++) {
						this.shoppingCard[i].list[ii].checked = true;
					}
				} 
                this.allChecked =true;
				this.totalprice = this.dataInfo.allGoodsMoney
			},
			msgtouchstart(e) {
				this.moveindex = e.currentTarget.dataset.msgindex;
				this.moveStart = e.changedTouches[0].pageX;
			},
			msgtouchend(e) {
				if (this.funBtnsWidthShow > 0) {
					this.funBtnsWidthShow = this.funBtnsWidth;
				} else {
					this.moveindex = '-';
				}
			},
			msgtouchmove(e) {
				var moveX = e.changedTouches[0].pageX - this.moveStart;
				if (moveX < 0) {
					moveX = moveX * -1;
					if (moveX > this.funBtnsWidth) {
						moveX = this.funBtnsWidth;
					}
					this.funBtnsWidthShow = moveX;
				} else {
					this.funBtnsWidthShow = 0;
				}
			},
			//计算总计函数
			countTotoal() {
				var total = 0;
				for (var i = 0; i < this.shoppingCard.length; i++) {
					for (var ii = 0; ii < this.shoppingCard[i].list.length; ii++) {
						if (this.shoppingCard[i].list[ii].checked) {
							total += Number(this.shoppingCard[i].list[ii].money) * Number(this.shoppingCard[i].list[ii].buyNum);
						}
					}
				}
				this.totalprice = total;
			},
			getChecked() {
				for (var i = 0; i < this.shoppingCard.length; i++) {
					this.allChecked = this.shoppingCard[i].list.every((item, index) => {
						return item.checked == true
					})
					if (this.allChecked == false) {
						return
					}
				}
			},
			numberChange(data) {
				this.shoppingCard[data[2]].list[data[1]].buyNum = data[0];
				//计算总价
				this.countTotoal();
			},
			addNum(item, index, indexItem,goods) {
				item.buyNum++
				this.shoppingCard[index].list[indexItem].buyNum = item.buyNum;
				item.moneyAll =  item.buyNum*item.money
                this.countTotoal();
				let data= {
					id:goods.id,
					name:goods.name,
					list:[item]
				}
				this.$Shop.setGoodsCart(data)
			},
			clearNum(item, index, indexItem,goods) {
				if (item.buyNum <= 1) {
					return
				}
				item.buyNum--
				this.shoppingCard[index].list[indexItem].buyNum = item.buyNum;
				item.moneyAll =  item.buyNum*item.money
                this.countTotoal();
                let data= {
                	id:goods.id,
                	name:goods.name,
                	list:[item]
                }
                this.$Shop.setGoodsCart(data)
			},
			removeGoods(e, id) {
				var index = e.currentTarget.id.replace('removeIndex_', '');
				index = index.split('_');
				var index1 = Number(index[0]);
				var index2 = Number(index[1]);
				uni.showModal({
					title: '确认提醒',
					content: '您确定要移除此商品吗？',
					success: (e) => {
						if (e.confirm) {
							this.shoppingCard[index1].list.splice(index2, 1);
							// 是否全部删除包含商铺
							if (this.shoppingCard[index1].list.length < 1) {
								this.shoppingCard.splice(index1, 1);
							}
							this.countTotoal();
							this.getChecked();
							let myJsonArray = JSON.parse(this.$Shop.getGoodsCart())
							myJsonArray.data.goodsList = this.shoppingCard;
							uni.setStorageSync('goodsCart',JSON.stringify(myJsonArray))
						}
					}
				})
			},
			checkout() {
				let data = this.shoppingCard;
				let goods_id = [];
				let newShopCard = []; //真实提交订单
				let carShop=[]; //提交到购物车
				for (var i = 0; i < data.length; i++) {
					if(data[i].checked){ //如果当前商铺被全选
						newShopCard.push(data[i])
					}else{ //否则开始遍历他下面的商品
						let is_true = data[i].list.every((item)=>{
							return item.checked==false
						})
						if(!is_true){
							let thisGoods=[],catGoods=[];
							data[i].list.forEach((item)=>{
								if(item.checked){
									thisGoods.push(item)
								}else{
									catGoods.push(item)
								}
							})
							newShopCard.push({
								checked:false,
								id:data[i].id,
								list:thisGoods,
								name:data[i].name
							});
							carShop.push({
								checked:false,
								id:data[i].id,
								list:catGoods,
								name:data[i].name
							});
						}else{
							carShop.push(data[i])
						}
					}
				}
                if(newShopCard.length<1){
                    uni.showToast({
                        title:'请选择商品',
                        icon:'none'
                    })
                    return
                }
				if(carShop.length>=1){
					this.$Shop.setStorage('shopCar',JSON.stringify(this.$Shop.changeGoodsCart(JSON.stringify(carShop))));
				}else{
                    this.$Shop.setStorage('shopCar','');
                }
				this.$Shop.setStorage('orderCar',JSON.stringify(this.$Shop.changeGoodsCart(JSON.stringify(newShopCard))));
                this.$Shop.navigateOrder();
			},
			// 店铺选中按钮状态切换
			shopChange(e) {
				var index = Number(e[1]);
				this.shoppingCard[index].checked = e[0];
				for (let i = 0; i < this.shoppingCard[index].list.length; i++) {
					this.shoppingCard[index].list[i].checked = e[0];
				}
				this.shoppingCard.splice(index, this.shoppingCard[index]);
				this.countTotoal();
				this.getChecked();
			},
			// 商品选中
			itemChange(e) {
				var indexs = e[1].toString();
				var index = indexs.split('-');
				index[0] = Number(index[0]);
				index[1] = Number(index[1]);
				this.shoppingCard[index[0]].list[index[1]].checked = e[0];
				this.shoppingCard.splice(index[0], this.shoppingCard[index[0]]);
				var checkedNum = 0;
				for (let i = 0; i < this.shoppingCard[index[0]].list.length; i++) {
					if (!this.shoppingCard[index[0]].list[i].checked) {
						checkedNum++;
					}
				}
				if (checkedNum < 1) {
					this.shoppingCard[index[0]].checked = true;
				} else {
					this.shoppingCard[index[0]].checked = false;
				}
				this.shoppingCard = this.shoppingCard;
				this.countTotoal();
				this.getChecked();
			},
			itemChangeAll(e) {
				this.selectText = e[0] ? '全选' : '全不选';
				for (var i = 0; i < this.shoppingCard.length; i++) {
					this.shoppingCard[i].checked = e[0];
					for (var ii = 0; ii < this.shoppingCard[i].list.length; ii++) {
						this.shoppingCard[i].list[ii].checked = e[0];
					}
				}
				this.countTotoal();
			},
			go(url) {
				uni.navigateTo({
					url
				})
			}
		},
		components: {
			gracePage,
			graceNumberBox,
			graceEmpty,
			graceCheckBtn,
		}
	}
</script>
<style lang="scss" scoped>
	page {
		background: #F8F8F8;
	}

	.empty-view {
		width: 280rpx;
		height: 280rpx;
		border-radius: 280rpx;
		background-color: #F6F7F8;
		margin-top: 30rpx;
	}

	.empty-img {
		width: 220rpx;
		height: 200rpx;
		margin: 40rpx;
		border-radius: 200rpx;
	}

	.grace-shoppingcard {
		background: #FFFFFF;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.grace-shopp-name {
		width: 500rpx;
	}

	.grace-shopp-go {
		width: 120rpx;
	}

	.grace-shoppingcard-goods {
		margin: 10rpx 0;
		display: flex;
		flex-wrap: nowrap;
	}

	.grace-shoppingcard-goods-checkbtn {
		width: 60rpx;
		flex-shrink: 0;
	}

	.grace-shoppingcard-goods-image {
		width: 120rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.grace-shoppingcard-goods-body {
		width: 100%;
	}

	.grace-shoppingcard-goods-title {
		line-height: 1.4em;
	}

	.grace-shoppingcard-goods-price {
		color: #ed1475;
		font-size: 32rpx;
		display: flex;
		flex-wrap: nowrap;
		justify-content: space-between;
	}

	.grace-shoppingcard-goods-number {
		padding: 2px 0;
		display: flex;
		justify-content: flex-start;
		align-items: center;

		.numbutton {
			font-size: 40rpx;
		}

		.num {
			padding: 10rpx 20rpx;
			background: #f1f2f3;

		}
	}

	.grace-shoppingcard-remove {
		float: right;
		display: block;
		text-align: right;
		line-height: 50rpx;
		margin-top: 30rpx;
		color: #CCCCCC;
		font-size: 24rpx;
	}

	.grace-shoppingcard-checkbtn {
		width: 152rpx;
		margin-left: 50rpx;
		flex-shrink: 0;
	}

	.grace-shoppingcard-count {
		width: 600rpx;
	}

	.grace-shoppingcard-checkout {
		width:184rpx;
		height: 100rpx;
		line-height: 100rpx;
		font-size: 28rpx;
		text-align: center;
		flex-shrink: 0;
	}

	.gg {
		font-size: 24rpx;
		color: #ababab;
		margin: 10rpx 0;
	}
</style>
